﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using IceDog.EFCore.ContosoUniversity.Data;
using IceDog.EFCore.ContosoUniversity.Models.SchoolViewModels;
using IceDog.EFCore.ContosoUniversity.Models;

namespace IceDog.EFCore.ContosoUniversity.Pages.Students
{
    public class EditVMModel : PageModel
    {
        private readonly IceDog.EFCore.ContosoUniversity.Data.SchoolContext _context;

        public EditVMModel(IceDog.EFCore.ContosoUniversity.Data.SchoolContext context)
        {
            _context = context;
        }

        [BindProperty]
        public StudentViewModel StudentVM { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var s= await _context.Student.FirstOrDefaultAsync(m => m.ID == id);
            StudentVM = new StudentViewModel
            {
                ID = s.ID,
                LastName = s.LastName,
                FirstMidName = s.FirstMidName,
                EnrollmentDate = s.EnrollmentDate
            };

            if (StudentVM == null)
            {
                return NotFound();
            }
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            var entry = _context.Attach(new Student());
            entry.CurrentValues.SetValues(StudentVM);
            entry.State = EntityState.Modified;
            await _context.SaveChangesAsync();
            return RedirectToPage("./Index");
        }

        private bool StudentViewModelExists(int id)
        {
            return _context.Student.Any(e => e.ID == id);
        }
    }
}
